const _Mongo = require('../../../Mongo')
const {
	getRandomId,
	encPwd,
} = require('../../../dbUtils')
const {
	getTime,
} = require('../../../dateUtils')
const {
	checkMongoIndex
} = require('./utils')

const modules = require('./col_module')
const funcs = require('./col_func')

module.exports = async function initModuleFunc(cmsMongo) {

	let funcCol = await cmsMongo.getCollection('func')
	let moduleCol = await cmsMongo.getCollection('module')
	await funcCol.deleteMany({})
	await moduleCol.deleteMany({})
	await initRole(cmsMongo)
	await checkIndex(cmsMongo)

	for (let i = 0; i < funcs.length; i++) {
		let func = funcs[i]
		func.create_time = getTime()
		func.modify_time = getTime()
		await funcCol.insertOne(func)
	}

	for (let i = 0; i < modules.length; i++) {
		let module = modules[i]
		module.create_time = getTime()
		module.modify_time = getTime()
		// let funcIds = await funcCol.find({
		// 	module_id: module.module_id,
		// }, {
		// 	func_id: 1
		// }).toArray()
		// funcIds = funcIds.map(val => val.func_id)
		// module.func_ids = funcIds
		await moduleCol.insertOne(module)
	}
}

async function initRole(cmsMongo) {
	let roleCol = await cmsMongo.getCollection('role')
	await roleCol.deleteMany({})
	await roleCol.insertOne({
		role_id: 'admin',
		role_name: '管理员',
		desc: '',
		create_time: getTime(),
		modify_time: getTime(),
		func_ids: -1,
	})
	await roleCol.insertOne({
		role_id: 'test',
		role_name: '测试',
		desc: '',
		create_time: getTime(),
		modify_time: getTime(),
		func_ids: ['func_list', 'func_query', 'test'],
	})
}

async function checkIndex(cmsMongo) {
	let r = checkMongoIndex.call(cmsMongo, [{
		col: 'role',
		index: 'role_id',
	}], {
		unique: true
	})
	let f = checkMongoIndex.call(cmsMongo, [{
		col: 'func',
		index: 'func_id',
	}], {
		unique: true
	})
	let m = checkMongoIndex.call(cmsMongo, [{
		col: 'module',
		index: 'module_id',
	}], {
		unique: true
	})
	return Promise.all([r, f, m])
}